<template>
  <view>
    <view class="search-bar" v-if="showSearchBar">
      <view class="cu-bar search bg-white ">
        <view class="search-form round">
          <text class="cuIcon-search"></text>
          <input @focus="searchBarFocus" @blur="serachBarBlur" :adjust-position="false" type="text" v-model="searchVal"
            :placeholder="placeholder" confirm-type="search" />
        </view>
        <view class="action" v-if="searchVal">
          <button class="cu-btn bg-blue shadow-blur round margin-right-xs" @click="toSearch">搜索</button>
        </view>
        <view class="action" v-else>
          <button class="cu-btn bg-white shadow-blur round  refresh" @click="$refs.bxList.onRefresh()"><text
              class="cuIcon-refresh"></text></button>

          <button class="cu-btn bg-blue shadow-blur round margin-right-xs" v-if="showCustomize&&disabled!==true"
            @click="clickcuButton">同步</button>


          <button class="cu-btn bg-blue shadow-blur round margin-right-xs" v-if="showAdd&&disabled!==true"
            @click="clickAddButton">添加</button>
        </view>
      </view>
      <!-- <view style="height: 100upx;width: 100%;"></view> -->
    </view>
    <bx-list ref="bxList" :ignoreStoreNo="ignoreStoreNo" :serviceName="serviceName" :disabled="detailDisabled||disabled" :srvApp="destApp"
      :condition="condition" :relation_condition="relation_condition" :pageType="pageType" :listType="'list'"
      :rowButtons="listConfig && listConfig.rowButton ? listConfig.rowButton : []" :showTab="false" :viewTemp="viewTemp"
      :listConfig="listConfig" :showButton="showRowButton" :fixed="true" :top="listTop" :searchWords="searchVal"
      :searchColumn="keyColumn" :tempWord="tempWord" :rownumber="10" :showFootBtn="showFootBtn"
      @click-list-item="clickItem" @list-change="listChange" @clickFootBtn="clickFootBtn" @loadEnd="loadEnd"
      v-if="listConfig&&listConfig.srv_cols"></bx-list>
  </view>
</template>

<script>
  import bxList from '@/components/bx-list/bx-list.vue';
  export default {
    components: {
      bxList
    },
    data() {
      return {
        ignoreStoreNo:false,
        serviceName: '',
        destApp: "",
        pageType: '',
        placeholder: '输入搜索关键词',
        listConfig: {},
        srv_cols: [],
        condition: [],
        relation_condition: null,
        pattern: {
          color: '#7A7E83',
          backgroundColor: '#fff',
          selectedColor: '#007AFF',
          buttonColor: '#007AFF'
        },
        fabContent: [],
        fabHorizontal: 'left',
        fabVertical: 'bottom',
        fabDirection: 'horizontal',
        listTop: 100,
        showRowButton: 'true',
        viewTemp: {
          // title: 'name',
          // tip: 'desc',
          // img: 'img',
          // price: 'current_price',
          // footer: 'shop_name'
        },
        publicButton: [],
        searchVal: '',
        keyColumn: '',
        showAdd: false,
        noData: false,
        showSearchBar: true,
        showFootBtn: true,
        tempWord: {},
        queryParams: {},
        queryOption: {},
        navigationBarTitle: null,
        showNavBack: false,
        showCustomize: false,
        disabled: false,
        detailDisabled: false
      };
    },
    onReachBottom() {
      if (!this.noData) {
        this.$refs.bxList.loadData();
        // this.$refs.bxList.getListData().then(data => {});
      }
    },
    onPullDownRefresh() {
      if (this.serviceName && this.$refs.bxList) {
        // this.getListV2();
        this.$refs.bxList.onRefresh();
      }
      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 200)
    },
    onShow() {
      if (this.serviceName && this.$refs.bxList) {
        // this.getListV2();
        this.$refs.bxList.onRefresh();
      }
    },

    onLoad(option) {
      if (option.disabled) {
        this.disabled = true
        this.detailDisabled = true
      }
      if (option.ignoreStoreNo) {
        this.ignoreStoreNo = true
      }
      if (option.detailDisabled) {
        this.detailDisabled = true
      }
      let query = {};
      // #ifdef H5
      this.listTop = 100;
      if (option.query) {
        query = JSON.parse(decodeURIComponent(option.query));
      } else {
        query = option;
      }
      // #endif
      // #ifdef MP-WEIXIN
      if (option.serviceName) {
        query = option;
      } else {
        query = JSON.parse(decodeURIComponent(option.query));
      }
      if (option.navigationBarTitle) {
        this.navigationBarTitle = option.navigationBarTitle;
        uni.setNavigationBarTitle({
          title: option.navigationBarTitle
        });
      }
      // #endif
      // #ifdef APP-PLUS
      query = option
      // #endif
      if (option.hasOwnProperty('showAdd')) {
        this.queryOption = option;
      }
      if (query.viewTemp) {
        // let viewTemp = this.getDecodeUrl(option.viewTemp);
        this.viewTemp = JSON.parse(query.viewTemp);
        if (this.viewTemp.title) {
          this.keyColumn = this.viewTemp.title;
        }
      }
      if (query.destApp) {
        this.destApp = query.destApp
        // uni.setStorageSync('activeApp', query.destApp);
      }
      this.showNavBack = query.showNavBack || false
      if (query.cond) {
        try {
          let cond = JSON.parse(decodeURIComponent(query.cond));
          if (Array.isArray(cond)) {
            cond.forEach(item => {
              if ((item.colName === 'create_user' || item.colName === 'openid' || item.colName ===
                  'glry') && item.value === 'user_no') {
                item.value = uni.getStorageSync('login_user_info').user_no;
              }
            });
            this.condition = cond;
          }
        } catch (e) {
          console.log(e);
          //TODO handle the exception
        }
        // this.condition = JSON.parse(this.getDecodeUrl(option.cond));
      }
      if (query.relation_condition) {
        try {
          let cond = JSON.parse(decodeURIComponent(query.relation_condition));
          if (Array.isArray(cond.data)) {
            cond.data.forEach(item => {
              if ((item.colName === 'create_user' || item.colName === 'openid' || item.colName ===
                  'glry') && item.value === 'user_no') {
                item.value = uni.getStorageSync('login_user_info').user_no;
              }
            });
            this.relation_condition = cond;
          }
        } catch (e) {
          console.log(e);
          //TODO handle the exception
        }
      }

      if (query.tempWord) {
        this.tempWord = JSON.parse(query.tempWord);
      }
      if (query.showRowButton) {
        this.showRowButton = query.showRowButton;
      }
      if (query.serviceName && query.pageType) {
        this.serviceName = query.serviceName;
        this.pageType = query.pageType;
        if (query.params) {
          let params = {};
          if (typeof query.params === 'string') {
            try {
              params = JSON.parse(query.params);
              this.queryParams = params;
            } catch (e) {
              //TODO handle the exception
            }
          }
        }
        this.getListV2();
      } else {
        // uni.showToast({
        // 	title:"无效页面",
        // 	icon:"Error"
        // })
        // setTimeout(()=>{
        // 	uni.hideToast()
        // 	uni.navigateBack()
        // },2000)
      }
    },
    methods: {
      toSearch() {
        this.$refs.bxList.toSearch();
      },
      loadEnd(e) {
        this.noData = true;
      },
      clickcuButton() {
        let _this = this
        let url = this.$api.serverURL + "/fyzhmd/operate/srvfyzhmd_yz_customer_data_sync"
        let store = sessionStorage.getItem("storeNo")
        let req = [{
          'serviceName': "srvfyzhmd_yz_customer_data_sync",
          'srvApp': "fyzhmd",
          "data": [{
            'client_id': "4a7112ba79b89d5b3e",
            'client_secret': "1622aaa3bddc5f0d7f24bd154b01fb64",
            'ktd_id': "98442311",
            'store_no': store
          }]
        }]
        this.$http.post(url, req).then(res => {
          console.log(res.data.state)
          if (res.data.state == 'SUCCESS') {
            uni.showToast({
              title: "同步成功",
              duration: 2000,
              success: function() {
                // _this.$refs.bxList.toSearch()
                _this.toSearch()
              }
            })
          }
        })
      },
      clickAddButton() {
        if (this.pageType === 'proc') {
          this.publicButton.map(item => {
            if (item.button_type === 'add' || item.button_type === 'apply') {
              uni.navigateTo({
                url: '/pages/public/proc/apply/apply?serviceName=' + item.service_name +
                  '&cond=' + decodeURIComponent(JSON.stringify(this.condition))
              });
            }
          });
        } else {
          this.publicButton.map(item => {
            if (item.button_type === 'add') {
              const params = {
                type: 'add',
                condition: [],
                serviceName: item.service_name,
                service_view_name: item.service_view_name
              };
              uni.navigateTo({
                url: '../formPage/formPage?serviceName=' + item.service_name +
                  `&type=add&destApp=${this.destApp}&cond=` + decodeURIComponent(JSON
                    .stringify(this.condition))
              });
            } else if (item.button_type === 'customize') {}
          });
        }
      },
      searchBarFocus(e) {
        console.log('searchBarFocus:', e);
      },
      serachBarBlur(e) {
        console.log('serachBarBlur:', e);
      },
      listChange(e) {
        console.log('listChange:', e);
      },
      clickItem(e) {
        if (this.pageType === 'proc') {
          uni.navigateTo({
            url: '/pages/public/proc/procDetail/procDetail?proc_instance_no=' + e.proc_instance_no
          });
        } else {
          let req = {
            button: {
              button_name: '详情',
              button_type: 'detail',
              service_name: this.serviceName
            },
            row: e
          };

          let url = `/pages/public/detail/detail?id=${e.id}&serviceName=${this.serviceName}`
          if (this.disabled == true || this.detailDisabled == true) {
            url += '&disabled=true'
          }

          // if(this.serviceName==='srvstore_member_mgmt_select'){
          //   url =   `/pages/specific/khxx/khxx?hy_no=${e.hy_no}`
          // }
          uni.navigateTo({
            url
          })
          try {
            // this.onButtonToUrl(req)
          } catch (e) {
            //TODO handle the exception
          }
        }
        console.log('click-list-item:', e);
      },
      async clickFootBtn(data) {
        let buttonInfo = this.deepClone(data.button);
        let rowData = this.deepClone(data.row);
        if (buttonInfo.operate_params && typeof buttonInfo.operate_params === 'string') {
          try {
            buttonInfo.operate_params = JSON.parse(buttonInfo.operate_params);
            if (Array.isArray(buttonInfo.operate_params.condition) && buttonInfo.operate_params.condition
              .length > 0) {
              buttonInfo.operate_params.condition.forEach(cond => {
                if (typeof cond.value === 'object' && cond.value.value_type === 'rowData') {
                  cond.value = data.row[cond.value.value_key];
                } else if (typeof cond.value === 'object' && cond.value.value_type ===
                  'constant') {
                  cond.value = cond.value.value;
                }
              });
            }
            if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params.data && Array.isArray(
                buttonInfo.operate_params.data) && buttonInfo.operate_params.data.length >
              0) {
              buttonInfo.operate_params.data.forEach(data => {
                if (typeof data === 'object') {
                  Object.keys(data).forEach(item => {
                    if (typeof data[item] === 'object' && data[item].value_type ===
                      'rowData') {
                      data[item] = rowData[data[item].value_key];
                    } else if (typeof data[item] === 'object' && data[item]
                      .value_type === 'constant') {
                      data[item] = data[item].value;
                    }
                  });
                }
              });
            }
            if (buttonInfo.operate_type === '操作' && buttonInfo.operate_mode === '静默操作') {
              let req = [{
                serviceName: buttonInfo.operate_service,
                condition: buttonInfo.operate_params.condition,
                data: buttonInfo.operate_params.data
              }];
              let app = this.destApp || uni.getStorageSync('activeApp');
              let url = this.getServiceUrl(buttonInfo.application ? buttonInfo.application : app,
                buttonInfo.operate_service, buttonInfo.servcie_type);
              let res = await this.$http.post(url, req);
              if (res.data.state === 'SUCCESS') {
                this.$refs.bxList.onRefresh();
              }
            } else if (buttonInfo.operate_type === '更新弹出') {
              let params = {
                type: buttonInfo.servcie_type,
                serviceName: buttonInfo.operate_service,
                main_table: buttonInfo.main_table,
                service: buttonInfo.service,
                button_type: buttonInfo.button_type,
              };
              if (Array.isArray(buttonInfo.operate_params.data) && buttonInfo.operate_params.data
                .length > 0) {
                params.defaultVal = buttonInfo.operate_params.data[0]
              }
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?serviceName=' +
                  buttonInfo.operate_service +
                  '&type=' +
                  buttonInfo.servcie_type +
                  '&params=' + JSON.stringify(params) +
                  '&cond=' +
                  decodeURIComponent(JSON.stringify(buttonInfo.operate_params.condition))
              });
            }
          } catch (e) {
            console.error(e);
            //TODO handle the exception
          }
        }

        if (this.pageType === 'proc') {
          if (data.button && data.button.button_type === 'edit' && data.row.proc_instance_no) {
            uni.navigateTo({
              url: '/pages/public/proc/procDetail/procDetail?proc_instance_no=' + data.row
                .proc_instance_no
            });
          }
        } else {
          this.onButtonToUrl(data).then(res => {
            if (data.button && data.button.button_type === 'delete') {
              if (res.state === 'SUCCESS') {
                this.$refs.bxList.onRefresh();
              } else {
                uni.showToast({
                  title: res.resultMessage,
                  icon: 'none'
                })
              }
            }
            if (data.button && data.button.button_type === 'detail') {
              let row = res.row;
              let btn = res.button;
              let params = {
                type: 'detail',
                condition: [{
                  colName: 'id',
                  ruleType: 'in',
                  value: row.id
                }],
                serviceName: btn.service_name,
                // defaultVal: row
              };
              // let url = `/pages/public/formPage/formPage?destApp=${this.destApp}&params=${JSON.stringify(params)}`
              // if (this.detailDisabled) {
              //   url += '&disabled=true'
              // }
              let url = `/pages/public/detail/detail?id=${row.id}&serviceName=${this.serviceName}`
              if (this.disabled == true || this.detailDisabled == true) {
                url += '&disabled=true'
              }
              uni.navigateTo({
                url
              });
            } else if (data.button && (data.button.button_type === 'duplicate' || data.button
                .button_type === 'duplicatedeep')) {
              let fieldsCond = []
              if (Array.isArray(self.condition)) {
                self.condition.forEach(item => {
                  fieldsCond.push({
                    column: item.colName,
                    value: item.value,
                    display: false
                  })
                })
              }

              let params = {
                type: 'add',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };

              Object.keys(params.defaultVal).forEach(key => {
                if (['id', 'modify_user_disp', 'modify_user', 'modify_time',
                    'create_user_disp', 'create_user', 'create_time'
                  ].includes(key) || !params.defaultVal[key]) {
                  delete params.defaultVal[key]
                }
              })

              uni.navigateTo({
                url: `/pages/public/formPage/formPage?destApp=${this.destApp}&params=${JSON.stringify(params)}`
              });

            } else if (data.button.servcie_type === 'select') {
              let params = {
                type: 'select',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };
            } else if (data.button.servcie_type === 'add' && data.button.button_type !== 'customize') {
              let params = {
                type: 'add',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?params=' + encodeURIComponent(JSON.stringify(params))
              });
            } else if (data.button && data.button.operate_type === '流程申请') {
              uni.navigateTo({
                url: '/pages/public/proc/apply/apply?serviceName=' + data.button
                  .operate_service
              });
            } else if (data.button && data.button.button_type === 'customize') {
              debugger
              let moreConfig = data.button.more_config;
              console.log(buttonInfo, rowData)
              if (moreConfig && typeof moreConfig === 'string') {
                try {
                  moreConfig = JSON.parse(moreConfig);
                } catch (e) {
                  //TODO handle the exception
                  console.log(e);
                }
              }
              if (data.button?.button_name === '支付码') {
                // 跳转到下单、生成支付码页面
                uni.navigateTo({
                  url: `/pages/public/payCode/payCode?id=${data.row.id}`
                })
                return
              } else if (data.button?.button_name === '填写问卷') {
                uni.navigateTo({
                  url: `/pages/specific/quest/quest?id=${data.row.id}`
                })
                return
              }

              let params = {
                type: buttonInfo.servcie_type == 'operate' ? 'update' : buttonInfo
                  .servcie_type,
                serviceName: buttonInfo.operate_service,
                main_table: buttonInfo.main_table,
                service: buttonInfo.service,
                button_type: buttonInfo.button_type == 'operate' ? 'update' : buttonInfo
                  .button_type,
              };
              if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params.data &&
                Array.isArray(buttonInfo.operate_params.data) && buttonInfo.operate_params.data
                .length > 0) {
                params.defaultVal = buttonInfo.operate_params.data[0]
              }
              if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params
                .condition &&
                Array.isArray(buttonInfo.operate_params.condition) && buttonInfo.operate_params
                .condition
                .length > 0) {
                params.condition = buttonInfo.operate_params.condition
              }
              let url = ''
              switch (buttonInfo.servcie_type) {
                case 'add':
                case 'operate':
                case 'update':
                  params.service = buttonInfo.operate_service
                  url =
                    `/pages/public/formPage/formPage?params=${JSON.stringify(params)}&destApp=${this.destApp}`
                  break;
              }
              switch (buttonInfo.operate_type) {
                case '详情跳转':
                  params.type = 'detail'
                  url =
                    `/pages/public/formPage/formPage?params=${JSON.stringify(params)}&destApp=${this.destApp}`
                  break;
                case '列表弹出':
                  let cond = buttonInfo.operate_params.condition
                  if (Array.isArray(cond)) {
                    url =
                      `/pages/public/list/list?pageType=list&serviceName=${buttonInfo.operate_service}&cond=${JSON.stringify(cond)}&destApp=${this.destApp}`
                  }
                  break;
                case 'URL跳转':
                  if (buttonInfo.pre_data_handle) {
                    // #ifdef H5
                    let arr = []
                    arr.push(rowData)
                    let result = eval("var fun=" + buttonInfo.pre_data_handle +
                      "(arr); fun")
                    if (result) {
                      let url = result.slice(result.indexOf('/pages/'))
                      uni.navigateTo({
                        url,
                        fail: () => {
                          window.location.href = result
                        }
                      })
                    }
                    // #endif
                  }

                  return
                case 'operate':

                  break;
              }
              if (params && url) {
                debugger
                uni.navigateTo({
                  url
                })
              }
            }
          });
        }
        console.log('clickFootBtn:', data);
      },
      async getListV2() {
        let app = this.destApp || 'fyzhmd';
        // let app = 'fyzhmd'
        let self = this;
        // let 
        let colVs = await this.getServiceV2(this.serviceName, 'list', this.pageType === 'proc' ? 'proclist' :
          'list', app);
        colVs.srv_cols = colVs.srv_cols.filter(item => item.in_list === 1 || item.in_list === 2);
        if (!this.navigationBarTitle) {
          uni.setNavigationBarTitle({
            title: colVs.service_view_name
          });
        }
        console.log('colVs', colVs);
        if (colVs.more_config) {
          try {
            colVs.moreConfig = JSON.parse(colVs.more_config)
          } catch (e) {
            //TODO handle the exception
          }
        }
        this.listConfig = colVs;
        if (this.pageType === 'proc') {
          this.showFootBtn = false;
        }
        this.publicButton = colVs.gridButton.filter(item => {
          if (item.permission === true) {
            switch (item.button_type) {
              case 'add':
              case 'apply':
                this.showAdd = true;
                return item;
                break;
              case 'select':
                this.showSearchBar = true;
                // #ifdef MP-WEIXIN
                this.listTop = 100;
                // #endif
                return item;
                break;
              case 'customize':
                this.showCustomize = true;
                return item;
                break;
            }
          }
        });
        return colVs;
      }
    }
  };
</script>

<style lang="scss">
  .add-button {
    position: fixed;
    bottom: 100upx;
    left: calc(50% - 50upx);
    width: 100upx;
    height: 100upx;
    border-radius: 50%;
    background-color: #0bc99d;
    z-index: 100;

    &::before {
      position: absolute;
      width: 8upx;
      height: 60upx;
      left: calc(50% - 4upx);
      top: 20upx;
      content: '';
      background-color: #fff;
    }

    &::after {
      position: absolute;
      width: 60upx;
      height: 8upx;
      content: '';
      top: calc(50% - 4upx);
      left: 20upx;
      background-color: #fff;
    }

    &:active {
      transform: rotate(45deg);
      transition: all 0.2s;
    }
  }

  .search-bar {
    flex: 1;

    .search-form {
      background-color: #F9F9FC;

    }

    .input-placeholder {
      color: #B4B6C9;
    }

    .action {
      .refresh {
        color: #333;
        font-size: 36rpx;
        padding: 0 20rpx;
        font-weight: bold;
      }
    }
  }
</style>
